﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Collections;
using System.Web;
using System.Xml;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using WF_DataAccess;
using WF_Business;

namespace Business.FlowOperation
{
    /// <!--
    /// 功能描述  : 工作流相关处理类。（类似ClsUserWorkFlow,为移动办公服务）
    /// -->
    public class WorkFlowHandle
    {
        /// <summary>
        /// 根据步骤id获取节点名
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetStepByWiid(long wiid)
        {
            string strSql = @"select wi.step from st_work_item wi where wi.wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据IID和岗位名称获取岗位CTLID
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public static string GetStepCtlid(long iid, string step)
        {
            string strSql = @"select ctlid from st_step where sname='" + step + "' and wid=(select wid from st_instance where iid=" + iid + ")";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取发送节点名
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetSendStepByWiid(long wiid)
        {
            string strSql = "select sendstep from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取发送节点名
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetSendStepCtlidByWiid(long wiid)
        {
            string strSql = "select sendstepctlid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取岗位组名
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetStepGroupByWiid(long wiid)
        {
            string strSql = "select StepGroup from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取节点控制id
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetStepCtlidByWiid(long wiid)
        {
            string strSql = "select stepctlid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取岗位组控制id
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetStepGroupCtlidByWiid(long wiid)
        {
            string strSql = "select stepgroupctlid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取节点控制id
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetUseridByWiid(long wiid)
        {
            string strSql = "select userid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据步骤id获取发送用户id
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static string GetSendUseridByWiid(long wiid)
        {
            string strSql = "select senduserid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据业务编号获取流程id
        /// </summary>
        /// <param name="iid">流程编号</param>
        /// <returns></returns>
        public static string GetWidByIid(long iid)
        {
            string strSql = "select wid from st_instance where iid='" + iid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据流程id获取流程名称
        /// </summary>
        /// <param name="wid">流程id</param>
        /// <returns></returns>
        public static string GetWnameByWid(string wid)
        {
            string strSql = "select wname from st_workflow where wid='" + wid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据wiid获取处理类型
        /// </summary>
        /// <param name="wiid"></param>
        /// <returns></returns>
        public static HandleType GetHandleTypeByWiid(long wiid)
        {
            string strSql = "select handle_type from xt_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            string tmp = ida.GetValue(strSql);
            if (string.IsNullOrEmpty(tmp))
                tmp = "0";
            return (HandleType)int.Parse(tmp);
        }
        

        /// <summary>
        /// 是否可以回退
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public static bool CanBack(string wid, string step)
        {
            string strSql = "select is_back from st_flow where wid='" + wid + "' and ename='" + step + "'";
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql) == "1";

        }

        /// <summary>
        /// 提交(带事务)
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="wiid">步骤编号</param>
        /// <param name="arrFus">流向用户结构体组</param>
        /// <param name="tran">事务</param>
        /// <param name="msg">返回信息</param>
        /// <returns></returns>
        protected static bool Submit(long iid, long wiid, FlowUserStruct[] arrFus, ref IDataAccess tran, ref string msg)
        {
            WorkItem workItem = new WorkItem();
            return workItem.Sumbit(iid, wiid, arrFus, ref tran, ref msg);
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="wiid">步骤编号</param>
        /// <param name="arrFus">流向用户结构体组</param>
        /// <param name="msg">返回信息</param>
        /// <returns></returns>
        protected static bool Submit(long iid, long wiid, FlowUserStruct[] arrFus, ref string msg)
        {
            WorkItem workItem = new WorkItem();
            return workItem.Sumbit(iid, wiid, arrFus, ref msg);
        }

        /// <summary>
        /// 回退
        /// </summary>
        /// <param name="wiid">步骤wiid</param>
        /// <param name="strRemark">回退留言</param>
        /// <returns></returns>
        public static bool Untread(long wiid, string strRemark)
        {
            WorkItem workItem = new WorkItem();
            return workItem.Untread(wiid, strRemark);
        }

        /// <summary>
        /// 退件
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="wiid">步骤编号</param>
        /// <param name="strRemark">退件留言</param>
        /// <returns></returns>
        public static bool Stop(long iid, long wiid, string strRemark)
        {
            WorkItem workItem = new WorkItem();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return workItem.Stop(iid, wiid, strRemark, -4, ref ida);
        }

        /// <summary>
        /// 获取节点上的资源树
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="wiid">节点编号</param>
        /// <param name="step">节点名称</param>
        /// <returns></returns>
        public static DataTable GetStepResource(long iid, long wiid, string step)
        {
            WorkFlowResource wfr = new WorkFlowResource();
            return wfr.ListInstanceStepResource(wiid.ToString(), step, iid.ToString());
        }

        /// <summary>
        /// 获取业务的资源树
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <returns></returns>
        public static DataTable GetInstanceResource(long iid)
        {
            WorkFlowResource wfr = new WorkFlowResource();
            return wfr.ListInstanceResource(iid.ToString());
        }

        /// <summary>
        /// 检查表单是否有编辑权限。
        /// </summary>
        /// <param name="wid">流程ID。</param>
        /// <param name="step">节点名称。</param>
        /// <param name="path">表单路径。</param>
        /// <param name="resValue">。</param>
        /// <param name="roles">角色集。</param>
        /// <returns></returns>
        public static bool CheckTableRight(string wid, string step, string path, string resValue, string[] roles)
        {
            string strSql = @"select Count(wid) from st_workflow_form_right " +
                       "Where wid='{0}' And step='{1}' And (form_path='{2}' OR formid='{3}') " +
                       "And roleid in ('{4}') And input_right>1";
            strSql = string.Format(strSql, wid, step, path, resValue, string.Join("','", roles));
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            int count = Convert.ToInt16(ida.GetValue(strSql));
            return (count > 0) ? true : false;
        }

        /// <summary>
        /// 获取回退用户。
        /// </summary>
        /// <param name="wiid">节点ID。</param>
        /// <param name="prevCtlid">回退节点的控制id。</param>
        /// <returns>用户列表。</returns>
        public static DataTable GetBackUsers(long iid, string wid, string Ctlid, string prevCtlid)
        {
            string strSql = @"select distinct userid,(select user_name from st_user where userid=t.userid) User_Name from st_work_item_hist t 
            where stepctlid='{0}' and wiid in(select prev_wiid from st_work_item_stack where iid='{1}' and step='{2}')
and userid in(select userid from st_user_group t Where gid In (Select gid From st_group_in_step Where wid='{3}' And stpname ='{0}'))";
            strSql = string.Format(strSql, prevCtlid, iid, Ctlid, wid);

            DataTable dtTemp = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dtTemp);

            if (dtTemp.Rows.Count == 0)
            {
                strSql = @"Select userid,user_name From st_user Where userid In(Select userid From st_user_group Where gid In
                    (Select gid From st_group_in_step Where wid='{0}' And stpname ='{1}')) Order By orderbyid";
                strSql = string.Format(strSql, wid, prevCtlid);
                ida.RunSql(strSql, out dtTemp);
            }
            return dtTemp;
        }

        /// <summary>
        /// 获取当前节点用户ID
        /// </summary>
        /// <param name="wiid"></param>
        /// <param name="iid"></param>
        /// <returns></returns>
        protected static string GetUserId(long wiid, long iid)
        {
            string strSql = "select t.userid from st_work_item t where t.wiid=" + wiid + " and t.iid=" + iid;

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="flow"></param>
        /// <returns></returns>
        public static DataTable GetRolesInStep(long iid, long wiid, string flow)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            if (flow == "岗位内提交") //如果是特殊的流向（岗位内提交），则例外处理
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("group_name");
                DataRow dr = dt.NewRow();
                dr["group_name"] = "岗位内提交";
                dt.Rows.Add(dr);
                dt.AcceptChanges();
                return dt;
            }
            string wid = WorkFlowResource.GetWidByIID(iid.ToString());
            string userId = GetUserId(wiid, iid).ToString();
            string strSql = "";

            if (GroupToGroup(wid, flow)) //根据部门过滤
            {
                strSql = "select group_name from st_group t where " + @"t.groupid in 
                    (select gid from st_group_in_step where wid='" + wid + @"' and stpname=
                    (select ename from st_flow where wid='" + wid + "' and fname='" + flow + @"')) and t.Department_id in 
                    (select Department_id from st_group where groupid in(select gid from st_user_group where userid='" + userId + "'))";
            }
            else
            {
                strSql = "select group_name from st_group where groupid in "
                    + "(select gid from st_group_in_step where wid='" + wid
                    + "' and stpname=(select ename from st_flow where wid='" + wid + "' and fname='" + flow + "')) order by sort";
            }

            DataTable dtTemp = new DataTable();
            ida.RunSql(strSql, out dtTemp);
            return dtTemp;
        }

        /// <summary>
        /// 是否结点组发送到结点组
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="flow"></param>
        /// <returns></returns>
        private static bool GroupToGroup(string wid, string flow)
        {
            string strSql = "select sname,ename from st_flow where wid='" + wid + "' and fname='" + flow + "'";
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            DataTable dtTemp = new DataTable();
            ida.RunSql(strSql, out dtTemp);

            strSql = "select extend_type from st_step where wid='" + wid + "' and ctlid='" + dtTemp.Rows[0]["sname"].ToString() + "'";
            string source = ida.GetValue(strSql);

            strSql = "select extend_type from st_step where wid='" + wid + "' and ctlid='" + dtTemp.Rows[0]["ename"].ToString() + "'";
            string target = ida.GetValue(strSql);
            return (source == "1" && target == "1");
        }

        /// <summary>
        /// 获取当前节点的用户id
        /// </summary>
        /// <param name="wiid">节点id</param>
        /// <returns></returns>
        protected static string GetCurrentUserid(long wiid)
        {
            string strSql = "select userid from st_work_item where wiid='" + wiid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 根据用户ID获取可以启动的流程
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <returns></returns>
        public static DataTable GetStartWorkflow(string userid)
        {
            string strSql = @"select wid,wname from st_workflow 
            where rot=0 and wid in(select wid from st_group_in_step where gid in
            (select gid from st_user_group where userid='" + userid + "') and step_type=0) and wname not in(select flowname from sys_business_type where code like '12%' or code like '13%')";

            DataTable dt = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 根据用户ID和业务类型获取可以启动的流程
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static DataTable GetStartWorkflow(string userid, string type)
        {
            string strSql = @"Select wid, wname From st_workflow s, sys_business_type t " +
                             "Where rot = 0 And wname = flowname And code Like '" + type + "%'";
            if (!string.IsNullOrEmpty(userid))
            {
                strSql += " And wid In (Select wid From st_group_in_step Where step_type = 0 And gid In (Select gid From st_user_group Where userid = '" + userid + "'))";
            }
            strSql += " Order By code";


            DataTable dt = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 获取最新版本的公文流程
        /// </summary>
        /// <returns></returns>
        public static DataTable GetNewestGWWorkflows()
        {
            string strSql = "Select wid,wname From st_workflow Where rot=0 and type In(11,12)";

            DataTable dt = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 根据流程名称获取最新版本的流程wid
        /// </summary>
        /// <param name="wname"></param>
        /// <returns></returns>
        public static string GetNewestWidByWname(string wname)
        {
            string strSql = @"select wid from st_workflow where rot=0 and wname='" + wname + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

       

        /// <summary>
        /// 根据角色名称获取下一岗位所有用户。
        /// </summary>
        /// <param name="iid">实例ID。</param>
        /// <param name="wiid">流转向ID。</param>
        /// <param name="step">结点名称。</param>
        /// <returns>用户列表。</returns>
        /// <!--
        /// 创建人  ：ChenDong
        /// 创建时间：2007-12-14
        /// -->
//        public static DataTable GetUsersInStep(long iid, long wiid, string step)
//        {
//            string strSql = string.Format(@"Select userid,user_name From st_user k 
//                Where userid In(Select userid From st_user_group Where gid In
//                (select groupid from st_group where group_name='{0}')) order by k.orderbyid", step);

//            if (step == "岗位内提交") //如果是特殊的流向（岗位内提交），则例外处理
//            {
//                //                strSql = string.Format(@"Select userid,user_name From st_user k where userid In
//                //                    (Select userid from st_work_item where active=-1 And iid='{0}'
//                //                    And step In(Select step From st_work_item Where wiid='{1}')) 
//                //                    order by k.orderbyid", iid, wiid);

//                strSql = string.Format(@"Select userid,user_name From st_user k where userid In
//                    (Select userid from st_work_item where iid='{0}' and wiid<>'{1}'
//                    And step In(Select step From st_work_item Where wiid='{1}')) 
//                    order by k.orderbyid", iid, wiid);
//            }

//            DataTable dtTemp;
//            SysParams.OAConnection().RunSql(strSql, out dtTemp);
//            return dtTemp;
//        }

        /// <summary>
        /// 获取回退留言
        /// </summary>
        /// <param name="wiid">节点id</param>
        /// <returns></returns>
        public static string GetBackRemark(string wiid)
        {
            string strSql = "select remark from st_work_item where wiid=" + wiid;

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        public static DataTable GetWorkItemList(string loginName)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            DataTable dt = new DataTable();
            string strSql = "Select userid,user_name From st_user Where login_name='" + loginName.ToUpper() + "'";
            ida.RunSql(strSql, out dt);

            string userId = userId = dt.Rows[0]["userid"].ToString();
            string userName = dt.Rows[0]["user_name"].ToString();

            string delegateTask = "";
            string delegateSql = "";
            strSql = "Select userid,delegate_task From st_delegate " +
                     "Where status=1 And end_time>=trunc(sysdate) And delegate_userid='" + userId + "'";
            ida.RunSql(strSql, out dt);
            foreach (DataRow dr in dt.Rows)
            {
                delegateTask = dr["delegate_task"].ToString();
                if (delegateTask == "全部")
                    delegateSql += "Or userid='" + dr["userid"] + "' ";
                else
                    delegateSql += "Or (userid='" + dr["userid"] + "' And wname='" + delegateTask + "') ";
            }

            string users = "";
            string typesname = "";
            strSql = "select * from st_delegate where status=1 and userid='" + userId + "' ";
            ida.RunSql(strSql, out dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string types = dt.Rows[i]["delegate_task"].ToString();
                    if (types == "全部")
                    {
                        users = " userid='1' ";
                        break;
                    }
                    else
                    {
                        if (i == (dt.Rows.Count - 1))
                        {
                            typesname = typesname + "'" + dt.Rows[i]["delegate_task"].ToString() + "'";
                            users = " userid='" + userId + "' and wname not in(" + typesname + ")";
                        }
                        else
                        {
                            typesname += "'" + dt.Rows[i]["delegate_task"].ToString() + "',";
                        }
                    }
                }
            }
            else
                users = " userid='" + userId + "' ";

            strSql = "Select * From sv_workitem_list t Where " + users + " " + delegateSql +
                     "Order by accepted_time desc ";
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        public static DataTable GetWorkItemSearchList(string loginName, string searchSql)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            DataTable dt = new DataTable();
            string strSql = "Select userid,user_name From st_user Where login_name='" + loginName.ToUpper() + "'";
            ida.RunSql(strSql, out dt);

            string userId = userId = dt.Rows[0]["userid"].ToString();
            string userName = dt.Rows[0]["user_name"].ToString();

            string delegateTask = "";
            string delegateSql = "";
            strSql = "Select userid,delegate_task From st_delegate " +
                     "Where status=1 And end_time>=trunc(sysdate) And delegate_userid='" + userId + "'";
            ida.RunSql(strSql, out dt);
            foreach (DataRow dr in dt.Rows)
            {
                delegateTask = dr["delegate_task"].ToString();
                if (delegateTask == "全部")
                    delegateSql += "Or userid='" + dr["userid"] + "' ";
                else
                    delegateSql += "Or (userid='" + dr["userid"] + "' And wname='" + delegateTask + "') ";
            }

            string users = "";
            string typesname = "";
            strSql = "select * from st_delegate where status=1 and userid='" + userId + "' ";
            ida.RunSql(strSql, out dt);

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string types = dt.Rows[i]["delegate_task"].ToString();
                    if (types == "全部")
                    {
                        users = " userid='1' ";
                        break;
                    }
                    else
                    {
                        if (i == (dt.Rows.Count - 1))
                        {
                            typesname = typesname + "'" + dt.Rows[i]["delegate_task"].ToString() + "'";
                            users = " userid='" + userId + "' and wname not in(" + typesname + ")";
                        }
                        else
                        {
                            typesname += "'" + dt.Rows[i]["delegate_task"].ToString() + "',";
                        }
                    }
                }
            }
            else 
                users = " userid='" + userId + "' ";

            delegateSql += " AND " + searchSql;
            strSql = "Select * From sv_workitem_list t Where " + users + " " + delegateSql +
                     "Order by accepted_time desc ";

            ida.RunSql(strSql, out dt);
            dt.TableName = "DataTable";

            return dt;
        }

        public static DataTable GetAllWorkItemSearchList(string loginName, string searchSql)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            DataTable dt = new DataTable();
            string strSql = "Select userid,user_name From st_user Where login_name='" + loginName.ToUpper() + "'";
            ida.RunSql(strSql, out dt);

            string userId = userId = dt.Rows[0]["userid"].ToString();
            string userName = dt.Rows[0]["user_name"].ToString();

            strSql = "Select * From sv_workitem_list t Where " + searchSql + " Order by accepted_time desc ";
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 设置打开状态
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="step"></param>
        public static void SetOpened(string iid, string wiid, string step)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise(true);
            try
            {
                //业务件一打开后避免其它人修改的处理。另外将UserId置为自己，一般情况下UserId就是自己，特殊情况为权力委托时，在打开前为
                //委托人，所以要在打开后置为被委托人。
                //这里做的处理是对同岗位上的其他人做限制，但不对多流向时的同级别的其他流向岗位的人员不做处理的
                string sql = string.Format("UPDATE ST_WORK_ITEM SET active=1 WHERE iid='{0}' and step='" + step + "'  AND wiid='{1}'", iid, wiid);
                ida.RunSql(sql);

                string result = "";
                AloneFlowHandle(iid, step, out result);

                if (result == "false")
                {
                    //其它流转置为-1
                    sql = string.Format("UPDATE ST_WORK_ITEM SET active=-1 WHERE iid='{0}'  and step='" + step + "'  AND wiid<>'{1}'", iid, wiid);
                    ida.RunSql(sql);
                }
                ida.Close(true);
            }
            catch
            {
                ida.Close(false);
            }
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        public static DataTable GetWorkItemCollect(string loginName)
        {
            string strSql = @"select item_type,item_type_name,count(*) amount from sv_workitem_list 
             where userid=(select userid from st_user where login_name='{0}')
             group by item_type,item_type_name order by item_type ";
            strSql = string.Format(strSql, loginName);

            DataTable dt = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dt);
            return dt;
        }

        /// <summary>
        /// 查询新Wiid
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static long newWiid(long iid)
        {
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            string strSql = @"select max(wiid)+1 from 
            (select wiid from st_work_item where iid='{0}' union
            select wiid from st_work_item_hist where iid='{0}' union
            select wiid from st_work_item_stack where iid='{0}')";
            strSql = string.Format(strSql, iid);

            long newWiid = Convert.ToInt64(ida.GetValue(strSql));
            return newWiid;
        }

        /// <summary>
        /// 获取前一步骤
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="ctlid"></param>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static DataTable GetPreviousStep(string wid, string ctlid, long iid)
        {
            string strSql = string.Empty;

            StepType stepType = WorkFlowStep.GetStepTypeByStep(wid, ctlid);
            strSql = @"Select * From st_step where wid='" + wid + "' and ctlid in (select sname from st_flow where is_back=1 and wid='" + wid + "' and ename='" + ctlid + "') ";
            if (stepType != StepType.MutiFlowEnd)
                strSql += @" and ctlid in(select sendstepctlid from st_work_item where stepctlid='" + ctlid + "' and iid='" + iid + @"'
                union select sendstepctlid from st_work_item_hist where stepctlid='" + ctlid + "' and iid='" + iid + "')";

            DataTable dtTemp = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dtTemp);
            return dtTemp;
        }

        /// <summary>
        /// 根据控制id获取节点名
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="ctlid"></param>
        /// <returns></returns>
        public static string GetStepNameByCtlid(string wid, string ctlid)
        {
            string strSql = "select sname from st_step where wid='" + wid + "' and ctlid='" + ctlid + "'";

            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            return ida.GetValue(strSql);
        }

        /// <summary>
        /// 获取已办业务的大类类型
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static DataTable GetBusinessTypeHanded(string loginName, string userId)
        {
            string strSql = @"select distinct item_type,item_type_name from sv_worklist_handled t where item_type not like '05%' and exists(select 1 from st_work_item_hist where iid=t.iid and userid='" + userId + @"') ";

            DataTable dtTemp = new DataTable();
            IDataAccess ida = SysParams.OAConnectionWithEnterprise();
            ida.RunSql(strSql, out dtTemp);
            return dtTemp;
        }

    
        public static void AloneFlowHandle(string iid, string step, out string result)
        {
            result = "";

            IDataAccess ida = SysParams.OAConnection();

            string sql = "NJGT_MOA.aloneflowhandle";
            IDataParameter[] idp = new OracleParameter[3];
            idp[0] = new OracleParameter("in_iid", OracleType.VarChar);
            idp[1] = new OracleParameter("in_step", OracleType.VarChar, 255);
            idp[2] = new OracleParameter("out_result", OracleType.VarChar, 255);
            idp[2].Direction = ParameterDirection.Output;
            idp[0].Value = iid;
            idp[1].Value = step;
            ida.RunProc(sql, ref idp);
            result = idp[2].Value.ToString();
        }

        public static void AloneFlowHandle2(string iid, string wiid, string step)
        {
            IDataAccess ida = SysParams.OAConnection();

            string sql = "NJGT_MOA.aloneflowhandle2";
            IDataParameter[] idp = new OracleParameter[3];
            idp[0] = new OracleParameter("in_iid", OracleType.VarChar);
            idp[1] = new OracleParameter("in_wiid", OracleType.VarChar, 255);
            idp[2] = new OracleParameter("in_step", OracleType.VarChar, 255);
            idp[0].Value = iid;
            idp[1].Value = wiid;
            idp[2].Value = step;
            ida.RunProc(sql, ref idp);
        }

        /// <summary>
        /// 根据iid获取案例主题信息和流程类别
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public DataTable GetTaskByiid(string iid)
        {
            string strSql = string.Format("select t.*,(select wname from st_workflow a where a.wid = t.wid) wname from st_instance t where iid = '{0}'",iid);

            DataTable dt = null;
            SysParams.OAConnection().RunSql(strSql, out dt);

            return dt;
        }

        /// <summary>
        /// 获取历史和当前审批记录
        /// </summary>
        /// <param name="strIid">用户id</param>
        /// <returns></returns>
        public DataTable GetFlowInfo(string strIid)
        {
            DataTable flowInfo = null;
            DataTable tempDt = null;
            string hist_sql = string.Format("select wiid,userid,(select user_name from st_user where st_user.userid = st_work_item_hist.userid) 经办人,STEP 岗位,ACCEPTED_TIME 接受时间,SUBMIT_TIME 提交时间,to_char(EXUSEDTIME) 办理时间 from st_work_item_hist where iid = '{0}' order by wiid", strIid);

            string work_item_sql = string.Format("select wiid,userid,(select user_name from st_user where st_user.userid = st_work_item.userid) 经办人,STEP 岗位,ACCEPTED_TIME 接受时间,ACCEPTED_TIME 提交时间,'办理中' 办理时间 from st_work_item where iid = '{0}' and active != -1 order by wiid", strIid);
            IDataAccess ida = SysParams.OAConnection();
            try
            {
                ida.RunSql(hist_sql, out flowInfo);
                ida.RunSql(work_item_sql, out tempDt);
            }
            catch (Exception eGetHist)
            {
                throw new Exception("重新取得历史表和当前表的办理数据出错！" + eGetHist.Message);
            }
            for (int i = 0; i < tempDt.Rows.Count; i++)
            {
                tempDt.Rows[i]["提交时间"] = System.DBNull.Value;
                flowInfo.Rows.Add(tempDt.Rows[i].ItemArray);
            }

            ida.Close();
            return flowInfo;
        }

        /// <summary>
        /// 根据iid获取案件的(当多流向时只能传到多流向开始节点)
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="userid">当前用户id</param>
        /// <param name="rstep">当前岗位id</param>
        /// <returns></returns>
        public DataTable GetBackStepByiid(string iid, string userid, string rstep)
        {
            DataTable tempDT = null;
            IDataAccess ida = SysParams.OAConnection();
            string sql = string.Format(@"select t.*  from st_work_item t  where iid = '{0}' and stepctlid='{1}'   and userid='{2}' ",iid,rstep,userid);
            ida.RunSql(sql, out tempDT);
            if (tempDT != null && tempDT.Rows.Count > 0)
            {
                StepType stepTypeByStep = WorkFlowStep.GetStepTypeByStep(Convert.ToInt64(iid), tempDT.Rows[0]["SENDSTEP"].ToString());
                if (stepTypeByStep == StepType.MutiFlowStart)
                {
                    sql = @"select * from (select wiid,
                                userid,(select user_name from st_user
                                where st_user.userid = st_work_item_hist.userid) 经办人,
                                STEP 岗位,ACCEPTED_TIME 接受时间,
                                SUBMIT_TIME 提交时间, to_char(EXUSEDTIME) 办理时间
                                from st_work_item_hist where iid = " + iid + @"
                                order by accepted_time desc) tw where 岗位='" + tempDT.Rows[0]["sendstep"].ToString() + "' and  rownum<=1";
                    ida.RunSql(sql, out tempDT);
                    if (tempDT != null && tempDT.Rows.Count > 0)
                    {
                        for (int i = 0; i < tempDT.Rows.Count; i++)
                        {
                            tempDT.Rows[i]["经办人"] = tempDT.Rows[i]["经办人"].ToString() + "(" + tempDT.Rows[i]["岗位"].ToString() + ")";
                        }
                    }
                    return tempDT;
                }
            }

            DataTable dt = null;
            dt = GetFlowInfo(iid);
            string userName = dt.Rows[dt.Rows.Count - 1]["userid"].ToString();
            string step = dt.Rows[dt.Rows.Count - 1]["岗位"].ToString();

            tempDT = dt.Clone();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int check = 1;
                for (int j = 0; j < tempDT.Rows.Count; j++)
                {
                    if ((dt.Rows[i]["userid"].ToString() == tempDT.Rows[j]["userid"].ToString()) && (dt.Rows[i]["岗位"].ToString() == tempDT.Rows[j]["岗位"].ToString()))
                    {
                        check = 0;
                        break;
                    }
                }
                if (check == 1)
                {
                    if ((dt.Rows[i]["userid"].ToString() != userName) || (dt.Rows[i]["岗位"].ToString() != step))
                    {
                        tempDT.Rows.Add(dt.Rows[i].ItemArray);
                    }
                }
            }

            for (int i = 0; i < tempDT.Rows.Count; i++)
            {
                tempDT.Rows[i]["经办人"] = tempDT.Rows[i]["经办人"].ToString() + "(" + tempDT.Rows[i]["岗位"].ToString() + ")";

            }
            return tempDT;
        }


    }

    /// <summary>
    /// 处理类型
    /// </summary>
    public enum HandleType
    {
        /// <summary>
        /// 普通
        /// </summary>
        Normal = 0,
        /// <summary>
        /// 补正材料
        /// </summary>
        SupplyMaterial = 1,
        /// <summary>
        /// 不予受理
        /// </summary>
        NoReceive = 2
    }
}